package uplink

import (
	"application/v3/internal/storage"
	"context"
	"github.com/brocaar/chirpstack-api/go/v3/as"
	"github.com/pkg/errors"
)

// Errors.
var (
	ErrAbort = errors.New("abort")
)

type uplinkContext struct {
	uplinkDataReq as.HandleUplinkDataRequest

	ctx           context.Context
	device        storage.Device
	application   storage.Application
	deviceProfile storage.DeviceProfile

	data       []byte
	objectJSON string
}

// Handle handles the uplink event.
func Handle(ctx context.Context, req as.HandleUplinkDataRequest) error {
	uplinkCtx := uplinkContext{
		ctx:           ctx,
		uplinkDataReq: req,
	}

	return HandleRunTasks(&uplinkCtx)
}

func HandleRunTasks(uplinkCtx *uplinkContext) error {
	for _, task := range tasks {
		if err := task(uplinkCtx); err != nil {
			if err == ErrAbort {
				return nil
			}
			return err
		}
	}

	return nil
}
